# -*- coding: UTF-8 -*-
import mqtt
import ujson
import utime as time
import _thread
from driver import GPIO
import lth_485
from driver import TIMER
import modem
import yun_network



# 云端下发控制继电器1开关灯
dy1 = GPIO()
dy1.open("dy1")

#服务质量
qos = 0
#topic
_get_topic = "attributes/push" 
_update_topic = "attributes"  #上报属性


# 定义subcribe的回调函数
def on_subcribe(topic,payload):
    global client
    global update_topic
    print("on_subcribe: topic is:" + topic)
    print("on_subcribe: payload is:" + payload)
    #平台下发的信息
    cloudmsg = ujson.loads(payload)
    if "switch" in cloudmsg:
        
        #如果平台下发继电器1高低电平指令，相应的改变继电器1所在的gpio口的电平值，
        #实现点亮/熄灭灯
        if cloudmsg["switch"] == 1:
            dy1.write(1)
        if cloudmsg["switch"] == 0:
            dy1.write(0)
        print('param_msg {}'.format(cloudmsg))
        client.publish(update_topic,update_data(),qos)
    else :
        pass

def get_mqtt_state():
    global mqtt_state
    return mqtt_state


#定时器，平台离线重启   
mqtt_state = 0
count_offline = 0
reconnect_state=0
netstate = 3
def timer_cb(args):
    global count_offline,reconnect_state,netstate,mqtt_state
    server_sta = get_mqtt_state()       
    if server_sta  == 0:  #平台离线
        count_offline += 1
        reconnect_state+=1
        print('count_offline:',count_offline)
        if count_offline>=30 and reconnect_state>=30:       #平台断开30秒重连
            reconnect_state=0
            mqtt_reconnect()
        if count_offline >= 160:     #平台离线160秒后重启设备
            print("offline 160 s")
            modem.reboot()
        else:
            pass
    else:
        count_offline = 0
    if yun_network.getNetFlag() ==False:
        print('netstate',netstate)
        netstate = 0
    if netstate ==0 and yun_network.getNetFlag() and get_mqtt_state()==0:
        netstate =1
        print('reconect-----------------')
        mqtt_reconnect()#连接thingscloud平台
    

def mqttloop_func(delay, id):
    global client
    global mqtt_state
    while True:
        time.sleep_ms(delay)
        ret =client.loop(800)     #检测平台是否连接，断网情况下不能连续调用
        # print("ret",ret)
        if ret < 0:
            mqtt_state = 0
            client.disconnect()
            print('------------------mqtt disconnect!')
            _thread.exit ()
        else:
            pass

def mqtt_reconnect():
    global client,mqttaddr, AccessToken, ProjectKey,serverport,client,mqtt_state,update_topic
    clientId = "test"       #可填写任意名称
    hearttime = 40
    #订阅/发布的topic
    get_topic = _get_topic
    update_topic = _update_topic
    print("mqtt_reconnect")
    client = mqtt.client(clientId)
    client.on_subcribe(on_subcribe)
    # 设置用户名和密码
    client.username_pw_set(AccessToken,ProjectKey)
    # 建立mqtt连接
    ret = client.connect(mqttaddr,serverport,hearttime)
    if ret == 0:
        mqtt_state = 1
        # 订阅服务
        client.subscribe(get_topic,qos)
        # 发布服务
        client.publish(update_topic,update_data(),qos)
        #创建mqtt接收数据任务，1s一次
        _thread.start_new_thread(mqttloop_func,(1000, 1))
    print("mqtt_state",mqtt_state)


#mqtt首次连接
def mqtt_connect(mqttaddr1, AccessToken1, ProjectKey1,serverport1):
    global mqttaddr, AccessToken, ProjectKey,serverport
    tim0 = TIMER(0)
    tim0.open(period=1000, mode=TIMER.PERIODIC, callback=timer_cb)      #开启定时器
    mqttaddr=mqttaddr1
    AccessToken=AccessToken1
    ProjectKey=ProjectKey1
    serverport=serverport1
    mqtt_reconnect()        #连接平台


#数据上报
def update_data():
    humidity,cTemp = lth_485.get_HC()
    light = lth_485.get_light()
    send_data = {
        "humidity":humidity,
        "temperature":cTemp,
        "lumen":light
    }
    #上报 格式 可以参考这句话
    MSG = ujson.dumps(send_data)
    print(MSG)
    return MSG

def update():
    global client,update_topic,qos
    client.publish(update_topic,update_data(),qos)
    print('update')



